import { sys } from "cc";
import { EngineConfig } from "./EngineConfig";
import { JhaoEncrypt } from "./JHaoEncrypt";

export default class LocalStorage {

    private static GamePreFlag: string = EngineConfig.Name

    public static isEncrypt: boolean = false;

    public static setStrig(key: string, value: string): void {
        let saveStr: string = value;
        if (this.isEncrypt) {
            saveStr = JhaoEncrypt.encode(value);
        }
        sys.localStorage.setItem(LocalStorage.GamePreFlag + key, saveStr);
    }

    public static getString(key: string): string {
        let str: string = sys.localStorage.getItem(LocalStorage.GamePreFlag + key);
        let result: string = str;
        if (str && str != '') {
            result = str;
            if (this.isEncrypt) {
                result = JhaoEncrypt.decode(str);
            }
        }
        return result
    }

    public static removeItem(key: string): void {
        sys.localStorage.removeItem(LocalStorage.GamePreFlag + key);
    }

    public static getInt(key: string): number {
        let tempValue: string = LocalStorage.getString(key);
        let result: number = 0;
        if (tempValue) {
            result = parseInt(tempValue);
        }
        return result;
    }

    public static setInt(key: string, value: number): void {
        LocalStorage.setStrig(key, value.toString());
    }

    public static getFloat(key: string): number {
        let tempValue: string = LocalStorage.getString(key);
        let result: number = 0;
        if (tempValue) {
            result = parseFloat(tempValue);
        }
        return result;
    }

    public static setFloat(key: string, value: number): void {
        LocalStorage.setStrig(key, value.toString());
    }

    public static getBoolean(key: string): boolean {
        let temp: number = LocalStorage.getInt(key);
        if (temp == 1) {
            return true;
        }
        return false;
    }

    public static setBoolean(key: string, value: boolean) {
        if (value) {
            LocalStorage.setInt(key, 1);
        } else {
            LocalStorage.setInt(key, 0);
        }
    }

    public static clear() {
        sys.localStorage.clear();
    }
}